# -*- coding: utf-8 -*-
from PyQt5.QtCore import Qt, pyqtSignal
from PyQt5.QtWidgets import QWidget, QLineEdit, QMessageBox, QAbstractItemView

from compoments.editWorkFillDialogImpl import EditWorkFillDialogImpl
from compoments.icon import AppIcon
from compoments.immediatelyFillDialogImpl import ImmediatelyFillDialogImpl
from compoments.table.qTableWidgetItem import MyQTableWidgetItem
from compoments.workFillWindow import Ui_Form
from service.ssoService import SSOService
from util import aesUtil, configJsonUtil, startUpUtil
from util.loggerFactory import Logger

logger = Logger()


class WorkFillWindowImpl(QWidget, Ui_Form):
    account_save_success_signal = pyqtSignal()
    program_changed_signal = pyqtSignal()

    def __init__(self, parent=None):
        super().__init__(parent)
        self.setupUi(self)
        # self.show()
        self.setWindowFlags(self.windowFlags() | Qt.WindowMaximizeButtonHint | Qt.WindowCloseButtonHint)
        self.setFixedSize(self.width(), self.height())
        self.setWindowTitle("工时填报")
        self.setWindowIcon(AppIcon())
        self.config = configJsonUtil.get_config()
        self.account_ = self.config['account']

        self.checkBox_password.stateChanged.connect(self.trigger_show_pass)
        self.pb_acount_save.clicked.connect(self.save_account)
        self.pb_acount_reset.clicked.connect(self.reset_account)

        self.account_save_success_signal.connect(self.saves_success_event)
        self.program_changed_signal.connect(self.load_program)

        self.pb_fill_immediately.clicked.connect(self.fill_immediately)
        self.pb_fill_save.clicked.connect(self.save_fill)

        self.toolButton_add.clicked.connect(self.add_program)
        self.toolButton_edit.clicked.connect(self.edit_program)
        self.toolButton_del.clicked.connect(self.del_program)

        self.tableWidget.cellChanged.connect(self.program_table_cell_change_event)
        self.load_account()
        self.load_work_fill_config()
        self.load_program()
        self.tableWidget.setFocusPolicy(Qt.NoFocus)
        self.tableWidget.setColumnHidden(0, True)
        self.tableWidget.setEditTriggers(QAbstractItemView.NoEditTriggers)

    def load_account(self):
        user_id = self.account_['user_id']
        password = self.account_['password']
        user_name = self.account_['user_name']
        self.user_id_input.setText(user_id)
        self.user_name_input.setText(user_name)
        if password is None or password == '':
            return
        decrypt_password = aesUtil.PrpCrypt.decrypt_password(user_id, password)
        self.password_input.setText(decrypt_password)

    def trigger_show_pass(self, state):
        if state == 2:
            self.password_input.setEchoMode(QLineEdit.Normal)
        else:
            self.password_input.setEchoMode(QLineEdit.Password)

    def reset_account(self):
        self.user_id_input.clear()
        self.user_name_input.clear()
        self.password_input.clear()
        self.save_account()

    def save_account(self):
        user_id = self.user_id_input.text()
        password_input_text = self.password_input.text()
        if password_input_text is None or password_input_text == '':
            encrypt_password = ''
        else:
            encrypt_password = aesUtil.PrpCrypt.encrypt_password(user_id, password_input_text)

        self.account_['user_id'] = user_id
        self.account_['user_name'] = self.user_name_input.text()
        self.account_['password'] = encrypt_password
        configJsonUtil.save_json(self.config)

        try:
            self.sso_service = SSOService(cache=False)
            self.account_save_success_signal.emit()
        except Exception as e:
            logger.error("{}".format(e))
            QMessageBox.warning(self, "提示", "账号密码验证失败：{}".format(e), QMessageBox.Yes, QMessageBox.Yes)

    def load_work_fill_config(self):
        work_hour = self.config['work_hour']
        self.fill_day_input.setText(work_hour['day_of_week'])
        self.fill_hour_input.setText(work_hour['hour'])
        self.fill_minute_input.setText(work_hour['minute'])
        self.auto_start_check.setChecked(work_hour['auto_start'])

    def save_fill(self):
        self.config['work_hour']['day_of_week'] = self.fill_day_input.text()
        self.config['work_hour']['hour'] = self.fill_hour_input.text()
        self.config['work_hour']['minute'] = self.fill_minute_input.text()
        start_check_is_checked = self.auto_start_check.isChecked()
        self.config['work_hour']['auto_start'] = start_check_is_checked
        if start_check_is_checked:
            startUpUtil.create_shot_cut()
        else:
            startUpUtil.cancel_create_shot_cut()
        configJsonUtil.save_json(self.config)
        QMessageBox.information(self, "提示", "保存成功", QMessageBox.Yes, QMessageBox.Yes)

    def saves_success_event(self):
        QMessageBox.information(self, "提示", "保存成功", QMessageBox.Yes, QMessageBox.Yes)

    def load_program(self):
        self.tableWidget.setRowCount(0)
        self.tableWidget.clearContents()
        programs = self.config['programs']
        for p in programs:
            row = self.tableWidget.rowCount()
            self.tableWidget.insertRow(row)
            self.tableWidget.setItem(row, 0, MyQTableWidgetItem(str(p['id'])))
            self.tableWidget.setItem(row, 1, MyQTableWidgetItem(p['xmbh']))
            self.tableWidget.setItem(row, 2, MyQTableWidgetItem(p['xmmc']))
            self.tableWidget.setItem(row, 3, MyQTableWidgetItem(p['rwbh']))
            self.tableWidget.setItem(row, 4, MyQTableWidgetItem(p['rwmc']))
            self.tableWidget.setItem(row, 5, MyQTableWidgetItem(str(p['gs'])))  # 工时
            self.tableWidget.setItem(row, 6, MyQTableWidgetItem(p['nr']))  # 内容
            self.tableWidget.setItem(row, 7, MyQTableWidgetItem(str(p['weight'])))  # 权重
            pass

    def add_program(self):
        # 打开新窗口
        self.editWorkFillDialogImpl = EditWorkFillDialogImpl(self)

    def edit_program(self):
        # 打开新窗口
        r = self.tableWidget.currentRow()
        if r == -1:
            QMessageBox.warning(self, "提示", "请选择行", QMessageBox.Yes, QMessageBox.Yes)
            return
        id = self.tableWidget.item(r, 0).text()
        self.editWorkFillDialogImpl = EditWorkFillDialogImpl(self, id)

    def del_program(self):
        r = self.tableWidget.currentRow()
        if r == -1:
            QMessageBox.warning(self, "提示", "请选择行", QMessageBox.Yes, QMessageBox.Yes)
            return
        ret = QMessageBox.question(self.parent(), "提示", "是否确认删除?", QMessageBox.Yes | QMessageBox.No,
                                   QMessageBox.Yes)
        if ret == QMessageBox.Yes:
            id = self.tableWidget.item(r, 0).text()
            index = 0
            for p in self.config['programs']:
                if str(p['id']) == id:
                    del self.config['programs'][index]
                    break
                index = index + 1
            configJsonUtil.save_json(self.config)
            self.tableWidget.removeRow(r)
            self.program_changed_signal.emit()

    def program_table_cell_change_event(self, row, col):
        pass

    def fill_immediately(self):
        self.immediatelyFillDialogImpl = ImmediatelyFillDialogImpl(self)

    def closeEvent(self, QCloseEvent):
        QCloseEvent.ignore()
        self.hide()
